package com.example.myapplication.view;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;

import android.os.Environment;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import com.example.myapplication.localdatabase.AppDatabase;
import com.example.myapplication.dao.FieldNotebookDao;
import com.example.myapplication.model.FieldNotebookEntity;
import com.example.myapplication.dao.MySQLConnection;
import com.example.myapplication.R;
import com.example.myapplication.model.FieldNotebook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test4 extends AppCompatActivity {
    private MySQLConnection dbConnection;
    private AppDatabase appDatabaseConnection; // 如果需要使用 Room 数据库
    private EditText etQueryName;
    private Button btnQuery;
    private  Button btnlocalQuery; // 本地查询按钮，如果需要的话
    private TextView tvPointId, tvName, tvRecordTime, tvLongitude, tvLatitude, tvOutcrop, tvPointMeaning, tvDescription,isuploaded;
    private ImageView ivImage;
    private ExecutorService executor;
    FieldNotebookDao dao;
    private Button btnExportPdf;
  ;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.test_4);

        appDatabaseConnection= Room.databaseBuilder(
          getApplicationContext(),
          AppDatabase.class,
          "field_notebook_db"
          ).fallbackToDestructiveMigration().build();
        dao = appDatabaseConnection.fieldNotebookDao();

        dbConnection = new MySQLConnection();
        executor = Executors.newSingleThreadExecutor();

        etQueryName = findViewById(R.id.et_query_name);
        btnQuery = findViewById(R.id.btn_query);//这个
        tvPointId = findViewById(R.id.tv_point_id);
        tvName = findViewById(R.id.tv_name);
        tvRecordTime = findViewById(R.id.tv_record_time);
        tvLongitude = findViewById(R.id.tv_longitude);
        tvLatitude = findViewById(R.id.tv_latitude);
        tvOutcrop = findViewById(R.id.tv_outcrop);
        tvPointMeaning = findViewById(R.id.tv_point_meaning);
        tvDescription = findViewById(R.id.tv_description);
        ivImage = findViewById(R.id.iv_image);
        isuploaded=findViewById(R.id.isuploaded);
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryRecord(); // 点击查询按钮时执行查询
            }
        });

        btnlocalQuery= findViewById(R.id.btn_localquery);
        btnlocalQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              localrecord(); //
            }
        });

        String queryName = getIntent().getStringExtra("query_name");
        if (queryName != null && !queryName.isEmpty()) {
            etQueryName.setText(queryName);
            localrecord(); // 自动触发本地查询
        }
        // 自动连接数据库
        connectToDatabase();
        //pdf导出,补的功能
        btnExportPdf = findViewById(R.id.btn_export_pdf);
        btnExportPdf.setOnClickListener(v -> exportToPdf());

    }
    // 对应界面UI


    public void connectToDatabase(){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                boolean success = dbConnection.connect();
                runOnUiThread(() -> Toast.makeText(Test4.this, success ? "数据库连接成功" : "数据库连接失败", Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void queryRecord() {
        String queryName = etQueryName.getText().toString().trim();//得名字
        if (queryName.isEmpty()) {
            Toast.makeText(this, "请输入点名称", Toast.LENGTH_SHORT).show();
            return;
        }

        executor.execute(() -> {
            FieldNotebook record = dbConnection.getRecordByname(queryName);
            boolean mt2=dbConnection.isRecordMorethan2(queryName);
            runOnUiThread(() -> {
                if (record == null) {
                    Toast.makeText(this, "无此记录", Toast.LENGTH_SHORT).show();
                    clearUI();
                    return;
                }
                if (mt2) {
                    Toast.makeText(this, "记录数量超过2条,尝试联系管理", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "查询成功", Toast.LENGTH_SHORT).show();
                }
                updateUI(record);
            });
        });
    }
    private void updateUI(FieldNotebook record) {
        tvPointId.setText("点位序号: " + record.pointId);
        tvName.setText("点名称: " + record.name);
        tvRecordTime.setText("记录时间: " + (record.recordTime != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.recordTime) : "无"));
        tvLongitude.setText("经度: " + record.longitude);
        tvLatitude.setText("纬度: " + record.latitude);
        tvOutcrop.setText("露头: " + (record.outcrop != null ? record.outcrop : "无"));
        tvPointMeaning.setText("点义: " + (record.pointMeaning != null ? record.pointMeaning : "无"));
        tvDescription.setText("描述: " + (record.description != null ? record.description : "无"));

        if (record.photo != null && record.photo.length > 0) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(record.photo, 0, record.photo.length);
            if (bitmap != null) {
                ivImage.setImageBitmap(bitmap);
            } else {
                ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
            }
        } else {
            ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
        }
    }

    private void updateUIlocal(FieldNotebookEntity record) {
        tvPointId.setText("点位序号: " + record.pointId);
        tvName.setText("点名称: " + record.name);
        tvRecordTime.setText("记录时间: " + (record.recordTime != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.recordTime) : "无"));
        tvLongitude.setText("经度: " + record.longitude);
        tvLatitude.setText("纬度: " + record.latitude);
        tvOutcrop.setText("露头: " + (record.outcrop != null ? record.outcrop : "无"));
        tvPointMeaning.setText("点义: " + (record.pointMeaning != null ? record.pointMeaning : "无"));
        tvDescription.setText("描述: " + (record.description != null ? record.description : "无"));
        isuploaded.setText("是否上传: " + (record.isuploaded == 1 ? "已上传" : "未上传"));
        if (record.photo != null && record.photo.length > 0) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(record.photo, 0, record.photo.length);
            if (bitmap != null) {
                ivImage.setImageBitmap(bitmap);
            } else {
                ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
            }
        } else {
            ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
        }
    }


    // 清空 UI
    private void clearUI() {
        tvPointId.setText("点位序号: ");
        tvName.setText("点名称: ");
        tvRecordTime.setText("记录时间: ");
        tvLongitude.setText("经度: ");
        tvLatitude.setText("纬度: ");
        tvOutcrop.setText("露头: ");
        tvPointMeaning.setText("点义: ");
        tvDescription.setText("描述: ");
        ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            dbConnection.disconnect();
            if (!executor.isShutdown()) {
                executor.shutdown();
                executor.awaitTermination(5, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            Toast.makeText(this, "清理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    private void localrecord(){

        String queryName = etQueryName.getText().toString().trim();//得名字
        if (queryName.isEmpty()) {
            Toast.makeText(this, "请输入点名称", Toast.LENGTH_SHORT).show();
            return;
        }


        executor.execute(() -> {
            FieldNotebookEntity   record = dao.findByName(queryName);
            int recordCount = dao.count(queryName);
            runOnUiThread(() -> {
                if (record == null) {
                    Toast.makeText(this, "无此记录", Toast.LENGTH_SHORT).show();
                    clearUI();
                }
                else if (recordCount>=2){

                    Toast.makeText(this, "记录数量超过2条,尝试联系管理", Toast.LENGTH_SHORT).show();
                    clearUI();
                }
                else {
                    updateUIlocal(record);
                }
            });
        });



    }



    private void exportToPdf() {
        if (tvName.getText().toString().equals("点名称: ") ||
                tvName.getText().toString().isEmpty()) {
            Toast.makeText(this, "没有可导出的数据", Toast.LENGTH_SHORT).show();
            return;
        }
//PdfDocument 是一个用于生成PDF文件的类。
//PdfDocument.PageInfo 用于定义PDF页面的大小和页码。
//PdfDocument.Page 表示PDF中的一页。
//page.getCanvas() 获取与当前页面关联的Canvas对象，你可以在上面绘制内容。
        executor.execute(() -> {
            try {
                PdfDocument document = new PdfDocument();
                int pageWidth = 595;
                int pageHeight = 842;
                PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create();
                PdfDocument.Page page = document.startPage(pageInfo);//：开始一个新的页面。这个方法返回一个PdfDocument.Page对象，表示当前页面。
                Canvas canvas = page.getCanvas();

                canvas.drawColor(Color.WHITE);

                Paint titlePaint = new Paint();
                titlePaint.setColor(Color.BLACK);
                titlePaint.setTextSize(24);
                titlePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));

                Paint textPaint = new Paint();
                textPaint.setColor(Color.BLACK);
                textPaint.setTextSize(14);

                Paint headerPaint = new Paint();
                headerPaint.setColor(Color.DKGRAY);
                headerPaint.setTextSize(16);
                headerPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));

                // 添加标题和页眉
                canvas.drawText("野外地质调查记录", (pageWidth - titlePaint.measureText("野外地质调查记录")) / 2, 50, titlePaint);
                canvas.drawLine(30, 60, pageWidth - 30, 60, textPaint);

                float yPos = 100;

                // 收集数据
                String pointId = tvPointId.getText().toString().replace("点位序号: ", "");
                String name = tvName.getText().toString().replace("点名称: ", "");
                String recordTime = tvRecordTime.getText().toString().replace("记录时间: ", "");
                String longitude = tvLongitude.getText().toString().replace("经度: ", "");
                String latitude = tvLatitude.getText().toString().replace("纬度: ", "");
                String outcrop = tvOutcrop.getText().toString().replace("露头: ", "");
                String pointMeaning = tvPointMeaning.getText().toString().replace("点义: ", "");
                String description = tvDescription.getText().toString().replace("描述: ", "");
                String uploaded = isuploaded.getText().toString().replace("是否上传: ", "");

                // 绘制数据 - 使用更清晰的格式
                canvas.drawText("点位信息", 50, yPos, headerPaint);
                yPos += 30;

                canvas.drawText("• 点位序号: " + pointId, 60, yPos, textPaint); yPos += 25;
                canvas.drawText("• 点名称: " + name, 60, yPos, textPaint); yPos += 25;
                canvas.drawText("• 记录时间: " + recordTime, 60, yPos, textPaint); yPos += 25;
                canvas.drawText("• 经纬度: " + longitude + ", " + latitude, 60, yPos, textPaint); yPos += 25;
                canvas.drawText("• 露头: " + outcrop, 60, yPos, textPaint); yPos += 25;
                canvas.drawText("• 点义: " + pointMeaning, 60, yPos, textPaint); yPos += 25;
                canvas.drawText("• 是否上传: " + uploaded, 60, yPos, textPaint); yPos += 40;

                // 描述部分 - 带标题
                canvas.drawText("详细描述", 50, yPos, headerPaint);
                yPos += 30;

                // 处理长描述（自动换行）
                TextPaint descPaint = new TextPaint(textPaint);
                StaticLayout descLayout = new StaticLayout(
                        description,
                        descPaint,
                        pageWidth - 100,
                        Layout.Alignment.ALIGN_NORMAL,
                        1.0f,
                        0.0f,
                        false
                );

                canvas.save();
                canvas.translate(60, yPos);
                descLayout.draw(canvas);
                canvas.restore();
                yPos += descLayout.getHeight() + 40;

                // 优化后的图片处理部分
                if (ivImage.getDrawable() != null) {
                    Bitmap imageBitmap = ((BitmapDrawable) ivImage.getDrawable()).getBitmap();
                    if (imageBitmap != null) {
                        // 添加图片标题
                        canvas.drawText("现场照片", 50, yPos, headerPaint);
                        yPos += 30;

                        // 计算合适的图片尺寸
                        float maxWidth = pageWidth - 100;
                        float maxHeight = pageHeight - yPos - 100;

                        // 保持宽高比缩放图片
                        float widthRatio = maxWidth / imageBitmap.getWidth();
                        float heightRatio = maxHeight / imageBitmap.getHeight();
                        float scale = Math.min(widthRatio, heightRatio);

                        int scaledWidth = (int) (imageBitmap.getWidth() * scale);
                        int scaledHeight = (int) (imageBitmap.getHeight() * scale);

                        // 在图片周围添加边框
                        Paint borderPaint = new Paint();
                        borderPaint.setColor(Color.LTGRAY);
                        borderPaint.setStyle(Paint.Style.STROKE);
                        borderPaint.setStrokeWidth(1);

                        // 居中显示图片
                        int left = (int) ((pageWidth - scaledWidth) / 2);
                        canvas.drawRect(left - 2, yPos - 2, left + scaledWidth + 2, yPos + scaledHeight + 2, borderPaint);
                        canvas.drawBitmap(Bitmap.createScaledBitmap(imageBitmap, scaledWidth, scaledHeight, true), left, yPos, textPaint);

                        yPos += scaledHeight + 40;
                    }
                }

                // 添加页脚
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String timestamp = sdf.format(new Date());
                canvas.drawText("生成时间: " + timestamp, pageWidth - 200, pageHeight - 30, textPaint);

                // 结束页面
                document.finishPage(page);

                // 保存文件
                File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                String fileName = "地质记录_" + name + "_" + System.currentTimeMillis() + ".pdf";
                File file = new File(downloadsDir, fileName);

                try (FileOutputStream fos = new FileOutputStream(file)) {
                    document.writeTo(fos);
                    runOnUiThread(() -> {
                        Toast.makeText(Test4.this,
                                "PDF已保存到下download目录: " + fileName,
                                Toast.LENGTH_LONG).show();
                    });
                } catch (IOException e) {
                    Log.e("PDF Export", "保存失败", e);
                }

                document.close();
            } catch (Exception e) {
                Log.e("PDF Export", "生成失败", e);
                runOnUiThread(() ->
                        Toast.makeText(Test4.this, "生成失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        });
    }
}
